package com.alibaba.shopping_file_service.service;

import com.alibaba.shopping_common.result.BusException;
import com.alibaba.shopping_common.result.CodeEnum;
import com.alibaba.shopping_common.service.FileUploadService;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;

import static com.alibaba.shopping_common.result.CodeEnum.FILE_DELETE_ERR;

/**
 * @ClassName FileUploadServiceImpl
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/10 10:42
 */
@DubboService
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FastFileStorageClient client;

    @Value("${fdfs.fileurl}")
    private String fileUrl;

    /**
     *
     * @param fileBytes 文件字节数组
     * @param fileName 文件名称
     * @return 文件保存的路径
     */
    @Override
    public String uploadFile(byte[] fileBytes, String fileName) {
        if (fileBytes.length !=0){
           try {
               // 1. 将文件字节数组转化成输入流
               ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
               // 2. 获取文件的后缀名
               String substring = fileName.substring(fileName.lastIndexOf(".") + 1);
               // 3. 上传文件
               StorePath storePath = client.uploadFile(inputStream, inputStream.available(), substring, null);
               // 4. 返回文件的路径
               System.out.println("返回文件的路径:"+fileUrl + "/" + storePath.getFullPath());
               return fileUrl + "/" + storePath.getFullPath();
           } catch (Exception e) {
               throw new BusException(CodeEnum.FILE_UPLOAD_ERR);
           }
        }else {
            throw new BusException(CodeEnum.FILE_UPLOAD_ERR);
        }
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     */
    @Override
    public void deleteFile(String filePath) {
        try {
            client.deleteFile(filePath);
        } catch (Exception e) {
            throw new BusException(FILE_DELETE_ERR);
        }
    }
}




